<?php
/**
 * | 节程 [ 节程赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 *  | Copyright (c) 2020~2029 温州惊蛰网络科技有限公司 All rights reserved.
 * +----------------------------------------------------------------------
 *  | Licensed 节程并不是自由软件，未经许可不能去掉节程相关版权
 * +----------------------------------------------------------------------
 */


namespace app\index\controller;


use app\utils\RedisUtil;
use think\Cache;
use think\facade\Db;
use think\response\Json;

class Total
{

    public function uvpv(string $path,string $deviceId) : Json{
        $response = request();
        $mall_id = $response->header('mid');
        $redis = new RedisUtil();
        $uvpv_info = $redis->get('uvpv_info'.date('Ymd'));
        !empty($uvpv_info[$mall_id]) && $array = $uvpv_info[$mall_id];
        $array = empty($array) ? ['data' => [],'details' => [],'device_id' => []] : $array;
        $array['data'][$path][] = $deviceId;
        $array['device_id'][] = $deviceId;
        $array['details'][] = ['path' => $path,'create_time' => date('Y-m-d H:i:s'),'details' => $deviceId];
        $uvpv_info[$mall_id] = $array;
        $redis->set('uvpv_info'.date('Ymd'),$uvpv_info,86400);
        $pv = 0;
        foreach ($array['data'] AS $key => $value){
            if ($key != 'index')
                $pv += count($value);
            else
                $pv += count(array_unique($value));
        }
        $uv = count(array_unique($array['device_id']));
        $array = $redis->get('uvpv_data'.date('Ymd'));
        empty($array) && $array = [];
        $array[$mall_id] = ['pv' => $pv,'uv' => $uv];
        $redis->set('uvpv_data'.date('Ymd'),$array,86400);
        $token = $response->header('Authorization');
        if (!empty($token)) {
            $user = \think\facade\Cache::store('redis')->get('INDEX:' . $token);
            $user = json_decode($user,true);
            if (!empty($user) && !empty(\think\facade\Cache::get($user['id'].'visit'))) {
                list($id,$agent_id) = \think\facade\Cache::get($user->id.'visit');
                $ip = $response->ip();
                $url = $response->pathinfo();
                $visit = ['ip' => $ip,'url' => 'index/'.$url,'create_time' => time(),'agent_id' => $agent_id,'user_id' => $id,'merchant_id' => $user->merchant_id ?? 0,'mall_id' => $mall_id,'mode' => 'index/'.$_SERVER['REQUEST_METHOD'], 'is_fission' => 1];
                Db::name('visit')->insert($visit);
            }
        }
        return json(['msg' => '成功'],HTTP_SUCCESS);
    }
}